﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Read.Api.Application.Command.RoleCommand;
using B.S.BaseData.Read.Api.Dtos;
using MediatR;
using SqlSugar;

namespace B.S.BaseData.Read.Api.Application.CommandHander.RoleHander
{
    public class GetRole2CommandHander : IRequestHandler<GetRole2Command, ApiPaging<List<GetRoleDto>>>
    {

        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public GetRole2CommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        public Task<ApiPaging<List<GetRoleDto>>> Handle(GetRole2Command request, CancellationToken cancellationToken)
        {
            ApiPaging<List<GetRoleDto>> paging = new ApiPaging<List<GetRoleDto>>();

            var linq = db.Queryable<User>()
                .InnerJoin<Role>((u, r) => u.UserId == r.UserId)
                       .Where((u, r) => r.IsDelete == false)
                       .Select((u, r) => new GetRoleDto
                       {
                           RoleId = r.RoleId,
                           RoleName = r.RoleName,
                           UserId = u.UserId,
                           CreateTime = r.CreateTime,
                           Updateid = r.Updateid,
                           UpdateTime = r.UpdateTime,
                           UserName = u.UserName
                       });

            paging.TotalCount = linq.Count();
            paging.TotalPage = (int)Math.Ceiling(paging.TotalCount * 1.0 / request.PageSize);
            var entity = linq.OrderBy(u => u.RoleId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            paging.Data = mapper.Map<List<GetRoleDto>>(entity);

            return Task.FromResult(paging);
        }
    }
}
